package com.vmladenov.cook.ui.recipes;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.vmladenov.cook.R;
import com.vmladenov.cook.core.Action;
import com.vmladenov.cook.core.DialogHelper;
import com.vmladenov.cook.core.Helpers;
import com.vmladenov.cook.core.OnSlideListener;
import com.vmladenov.cook.core.SlideGestureDetector;
import com.vmladenov.cook.core.adapters.RecipeCommentAdaptor;
import com.vmladenov.cook.core.db.proxy.RecipeComment;
import com.vmladenov.cook.core.html.Recipe;

public final class ViewRecipeActivity extends Activity implements OnSlideListener
{
	ProgressDialog progressDialog = null;
	Recipe recipe = null;
	private SlideGestureDetector detector;
	private ViewFlipper flipper;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.recipeview);
		this.detector = new SlideGestureDetector(this, this);
		this.flipper = (ViewFlipper) findViewById(R.id.flipper);

		View.OnTouchListener onTouchListener = new View.OnTouchListener()
		{

			@Override
			public boolean onTouch(View v, MotionEvent event)
			{
				return detector.onTouchEvent(event);
			}
		};

		ScrollView scroller = (ScrollView) findViewById(R.id.scrollView1);
		scroller.setOnTouchListener(onTouchListener);

		changeControlsVisibility(View.INVISIBLE);

		Intent intent = getIntent();
		Bundle bundle = intent.getBundleExtra("RECIPE_ID");
		long id = bundle.getLong("id");
		loadRecipe(id);

		ListView lv = (ListView) findViewById(R.id.listComments);
		lv.setOnTouchListener(onTouchListener);
		registerForContextMenu(lv);
		
		DialogHelper.showViewRecipeInfo(this);
	}

	Handler loadRecipeHandler = new Handler()
	{
		public void handleMessage(android.os.Message msg)
		{
			if (progressDialog != null) progressDialog.dismiss();
		};
	};

	Handler loadCommentsHandler = new Handler();

	private void loadRecipe(final long id)
	{
		progressDialog = ProgressDialog.show(ViewRecipeActivity.this, getString(R.string.loadingRecipe), getString(R.string.loading), false);

		Thread readRecipeThread = new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				recipe = Helpers.getDataHelper().RecipesRepository.getRecipe(id);
				loadRecipeHandler.post(new Runnable()
				{
					@Override
					public void run()
					{
						showRecipe();
					}
				});
				loadRecipeHandler.sendEmptyMessage(0);
			}
		});
		readRecipeThread.start();

		loadComments(id);
	}

	private void loadComments(final long id)
	{
		Thread readRecipeCommentsThread = new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				final RecipeComment[] comments = Helpers.getDataHelper().RecipesRepository.getRecipeComments(id);
				if (comments == null) return;
				loadCommentsHandler.post(new Runnable()
				{
					@Override
					public void run()
					{
						RecipeCommentAdaptor adapter = new RecipeCommentAdaptor(ViewRecipeActivity.this, comments);
						ListView lv = (ListView) findViewById(R.id.listComments);
						lv.setAdapter(adapter);
					}
				});
			}
		});
		readRecipeCommentsThread.start();
	}

	private void changeControlsVisibility(int visibility)
	{
		TextView title = (TextView) findViewById(R.id.txtRecipeTitle);
		TextView products = (TextView) findViewById(R.id.txtRecipeProducts);
		TextView description = (TextView) findViewById(R.id.txtRecipeDescription);
		ImageView image = (ImageView) findViewById(R.id.imgRecipePicture);

		title.setVisibility(visibility);
		products.setVisibility(visibility);
		description.setVisibility(visibility);
		image.setVisibility(visibility);
	}

	private void showRecipe()
	{
		if (recipe == null) return;

		TextView title = (TextView) findViewById(R.id.txtRecipeTitle);
		TextView products = (TextView) findViewById(R.id.txtRecipeProducts);
		TextView description = (TextView) findViewById(R.id.txtRecipeDescription);
		final ImageView image = (ImageView) findViewById(R.id.imgRecipePicture);

		title.setText(recipe.getTitle());
		products.setText(recipe.getProducts());
		String desc = recipe.getDescription() + "\n" + recipe.getNotes();
		description.setText(desc);
		Helpers.setImageFromUrlAsync(image, recipe.getImageUrl());

		changeControlsVisibility(View.VISIBLE);
	}

	// region Events

	@Override
	public Object onRetainNonConfigurationInstance()
	{
		return recipe;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
	{
		super.onCreateContextMenu(menu, v, menuInfo);
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
		ListView lv = (ListView) v;
		RecipeComment recipeComment = (RecipeComment) lv.getAdapter().getItem(info.position);
		if (recipeComment.UserId == Helpers.getCurrentUser().getId())
		{
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.recipe_comment_context_menu, menu);
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item)
	{
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		ListView lv = (ListView) findViewById(R.id.listComments);
		RecipeComment recipeComment = (RecipeComment) lv.getAdapter().getItem(info.position);
		switch (item.getItemId())
		{
			case R.id.miModify:
				DialogHelper.showAddCommentDialog(ViewRecipeActivity.this, recipeComment, recipe.getId(), new Action()
				{
					@Override
					public void Execute()
					{
						loadComments(recipe.getId());
					}
				});
				return true;
			case R.id.miDelete:
				Helpers.getDataHelper().RecipesRepository.removeRecipeComment(recipeComment.ID);
				loadComments(recipe.getId());
				return true;
			default:
				return false;
		}
	}

	public void onFavoriteClick()
	{
		if (!Helpers.isLoggedIn())
		{
			DialogHelper.showErrorDialog(ViewRecipeActivity.this, getString(R.string.registerToContinue));
			return;
		}
		if (recipe != null && recipe.getId() > 0)
		{
			recipe.setIsFavorite(!recipe.getIsFavorite());
			if (recipe.getIsFavorite())
			{
				Helpers.getDataHelper().RecipesRepository.addFavorite(recipe.getId());
			}
			else
			{
				Helpers.getDataHelper().RecipesRepository.removeFavorite(recipe.getId());
			}
		}
	}

	public void onAddComment()
	{
		if (!Helpers.isLoggedIn())
		{
			DialogHelper.showErrorDialog(ViewRecipeActivity.this, getString(R.string.registerToContinue));
			return;
		}
		if (recipe != null && recipe.getId() > 0)
		{
			DialogHelper.showAddCommentDialog(ViewRecipeActivity.this, null, recipe.getId(), new Action()
			{
				@Override
				public void Execute()
				{
					loadComments(recipe.getId());
				}
			});
		}
	}

	public void onRate()
	{
		if (!Helpers.isLoggedIn())
		{
			DialogHelper.showErrorDialog(ViewRecipeActivity.this, getString(R.string.registerToContinue));
			return;
		}
		if (recipe != null && recipe.getId() > 0)
		{
			DialogHelper.showRatingDialog(ViewRecipeActivity.this, recipe);
		}
	}

	public void onShare()
	{
		Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
		shareIntent.setType("text/plain");
		shareIntent.putExtra(Intent.EXTRA_SUBJECT, recipe.getTitle());
		shareIntent.putExtra(Intent.EXTRA_TEXT, recipe.getUrl());
		startActivity(Intent.createChooser(shareIntent, this.getString(R.string.share_title)));
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.recipe_view_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case R.id.mi_favorite:
				onFavoriteClick();
				return true;
			case R.id.mi_add_comment:
				onAddComment();
				return true;
			case R.id.mi_share:
				onShare();
				return true;
			case R.id.mi_rate:
				onRate();
				return true;
			default:
				return false;
		}
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu)
	{
		if (recipe == null) return false;
		MenuItem miFavorite = menu.findItem(R.id.mi_favorite);
		// MenuItem miNotes = menu.findItem(R.id.mi_add_comment);
		// MenuItem miRate = menu.findItem(R.id.mi_rate);

		Boolean isFavorite = recipe.getIsFavorite() == null ? false : recipe.getIsFavorite();
		// Boolean hasNote = recipe.getUserNotes() == null ||
		// recipe.getUserNotes().length() == 0 ? false : true;
		if (isFavorite)
		{
			miFavorite.setIcon(R.drawable.remove_favorite);
		}
		else
		{
			miFavorite.setIcon(R.drawable.add_favorite);
		}

		// if (hasNote)
		// {
		// miNotes.setIcon(R.drawable.notes);
		// }
		// else
		// {
		// miNotes.setIcon(R.drawable.nonotes);
		// }

		return true;
	}

	// endregion

	// region Swipe

	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		return this.detector.onTouchEvent(event);
	}

	final long animationDuration = 150;

	private Animation inFromRightAnimation()
	{
		Animation inFromRight = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, +1.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f);
		inFromRight.setDuration(animationDuration);
		inFromRight.setInterpolator(new AccelerateInterpolator());
		return inFromRight;
	}

	private Animation outToLeftAnimation()
	{
		Animation outtoLeft = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, -1.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f);
		outtoLeft.setDuration(animationDuration);
		outtoLeft.setInterpolator(new AccelerateInterpolator());
		return outtoLeft;
	}

	private Animation inFromLeftAnimation()
	{
		Animation inFromLeft = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, -1.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f);
		inFromLeft.setDuration(animationDuration);
		inFromLeft.setInterpolator(new AccelerateInterpolator());
		return inFromLeft;
	}

	private Animation outToRightAnimation()
	{
		Animation outtoRight = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, +1.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f);
		outtoRight.setDuration(animationDuration);
		outtoRight.setInterpolator(new AccelerateInterpolator());
		return outtoRight;
	}

	@Override
	public void onSlideLeft()
	{
		flipper.setInAnimation(inFromLeftAnimation());
		flipper.setOutAnimation(outToRightAnimation());
		flipper.showPrevious();
	}

	@Override
	public void onSlideRight()
	{
		flipper.setInAnimation(inFromRightAnimation());
		flipper.setOutAnimation(outToLeftAnimation());
		flipper.showNext();
	}

	// endregion

}
